package com.idopartx.phonelightning.ui;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.dotools.privacy.AgreementDialog;
import com.dotools.toutiaolibrary.TTManagerHolder;
import com.dotools.umlibrary.UMPostUtils;
import com.ido.news.splashlibrary.callback.SplashCallBack;
import com.ido.news.splashlibrary.view.SplashView;
import com.ido.news.splashlibrary.view.SplashViewBuilder;
import com.idopartx.phonelightning.MainActivity;
import com.idopartx.phonelightning.R;
import com.idopartx.phonelightning.application.CLApplication;
import com.idopartx.phonelightning.common.Constant;
import com.idopartx.phonelightning.ui.permissionguide.Help1PermissionActivity;
import com.idopartx.phonelightning.ui.permissionguide.Help3PermissionActivity;
import com.idopartx.phonelightning.ui.permissionguide.HelpVivoPermissionActivity;
import com.idopartx.phonelightning.utils.PermissionUtils;
import com.idopartx.phonelightning.utils.PreferenceSetting;
import com.tencent.mmkv.MMKV;
import com.tools.permissions.library.DOPermissions;
import com.tools.permissions.library.Permissions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jinks on 16/3/28.
 */
public class SplashActivity extends FragmentActivity implements DOPermissions.DOPermissionsCallbacks {
    private FrameLayout mRelativeLayout;
    private SplashView idoSplash;
    private boolean isShowed = false;
    private boolean isIcon = true;
    private Handler mHandler;
    private String[] pers = new String[]{Permissions.READ_EXTERNAL_STORAGE, Permissions.WRITE_EXTERNAL_STORAGE, Permissions.READ_PHONE_STATE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        mRelativeLayout = findViewById(R.id.container);
        mHandler = new Handler();
        Log.e("aabb", Constant.TT_APPID + "   mmmmmmm");
        if (getIntent() != null) {
            isIcon = getIntent().getBooleanExtra("isIcon", true);
            Map map = new HashMap<String, String>();
            if (isIcon) {
                map.put("splash", "isIcon");
            } else {
                map.put("splash", "noIcon");
            }
            UMPostUtils.INSTANCE.onEventMap(this, "flash_show_in_app", map);
            UMPostUtils.INSTANCE.onEvent(this, "splash_activity_create");
        }


//        return;

        creat();
        if (MMKV.defaultMMKV().decodeBool("isFirstJoin", true)) {
            AgreementDialog agreementDialog = new AgreementDialog(this, getString(R.string.privacy_policy_text));
            agreementDialog.setOkClick(new AgreementDialog.OnBtnClickListener() {
                @Override
                public void onOkClick() {
                    MMKV.defaultMMKV().encode("isFirstJoin", false);
                    ((CLApplication) getApplication()).init();
                    initPermissionAndShowSplash();
                }

                @Override
                public void onUnOKClick() {
                    MMKV.defaultMMKV().encode("isFirstJoin", true);
//                    SharedPref.getInstance(SplashActivity.this).putBoolean("isFirstJoin", false);
                }
            });

            mHandler.postDelayed(() -> {
                agreementDialog.show();
            }, 300);
        } else {
            showsp();
        }
        UMPostUtils.INSTANCE.pushAppStart(getApplicationContext());

//        Intent intent = new Intent(this, MainActivity.class);
//        this.startActivity(intent);
//        this.finish();
    }

    private void initPermissionAndShowSplash() {
//        if (Build.VERSION.SDK_INT >= 23) {
//            //申请权限
//            if (DOPermissions.getInstance().hasPermission(SplashActivity.this, pers)) {
//                showsp();
//            } else {
//                DOPermissions.getInstance().getPermissions(SplashActivity.this, "", 11, pers);
//            }
//        } else {
//        }
        showsp();
    }

    private void showsp() {
        if (!isShowed) {
            isShowed = true;
            handler.postDelayed(runnable, 300);
        }
    }

    private void creat() {
        initRunnable();
        idoSplash = new SplashViewBuilder(SplashActivity.this)
                .setViewGroup(mRelativeLayout)
                .setTxNativePosID(Constant.tx_splash_key)
                .setTtAppId(Constant.TT_APPID)
//                .setTtNativePosID(Contants.tt_splash_key)   //原开屏位
                .setTtNativePosID(Constant.TT_SPLASH_ID)   //点睛专用开屏位
                .setIsShowIcon(false)
                .setIsFullShow(true)
                .setShowClickEye(true)
                .setClickEyePosition(1)
                .setCallBack(new SplashCallBack() {
                    @Override
                    public void onSuccess() {
                        jumpWhenCanClick();
                    }

                    @Override
                    public void onFailed() {
                        jumpWhenCanClick();
                    }

                    @Override
                    public void onSkip() {
                        jumpWhenCanClick();
                    }

                    @Override
                    public void onClick() {
                        jumpWhenCanClick();
                    }
                }).creat();

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return event.getKeyCode() != KeyEvent.KEYCODE_BACK && super.onKeyDown(keyCode, event);
    }

    public boolean canJumpImmediately = false;

    private void jumpWhenCanClick() {
        if (canJumpImmediately) {
            if (isIcon) {


                if (!PreferenceSetting.INSTANCE.isFirst(this)) {
//                if (MMKV.defaultMMKV().decodeBool(Constant.MMKV_IS_GUIDE, false)) {
                    Intent intent = new Intent(this, MainActivity.class);
                    intent.putExtra("isSplash", true);
                    startActivity(intent);
                    finish();
                } else {
                    if (PermissionUtils.isHuaWeiDevice() || (PermissionUtils.isOppoDevice() && Build.VERSION.SDK_INT >= 29)) {
                        Intent intent = new Intent(this, Help1PermissionActivity.class);
                        this.startActivity(intent);
                    } else if (PermissionUtils.isXiaomiDevice() || (PermissionUtils.isOppoDevice() && Build.VERSION.SDK_INT >= 27)) {
                        Intent intent = new Intent(this, Help3PermissionActivity.class);
                        this.startActivity(intent);
                    } else {
                        Intent intent = new Intent(this, HelpVivoPermissionActivity.class);
                        this.startActivity(intent);
                    }

                }
            }
            this.finish();
        } else {
            canJumpImmediately = true;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (canJumpImmediately) {
            jumpWhenCanClick();
        }
        canJumpImmediately = true;
        UMPostUtils.INSTANCE.onActivityResume(SplashActivity.this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJumpImmediately = false;
        UMPostUtils.INSTANCE.onActivityPause(SplashActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DOPermissions.getInstance().setRequestPermission(this, requestCode, permissions, grantResults);
    }

    /**
     * 权限申请成功
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        showsp();
    }

    /**
     * 权限申请失败
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        showsp();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    private Runnable runnable = null;
    private int count = 0;
    private Handler handler = new Handler();

    private void initRunnable() {
        if (runnable == null) {
            runnable = () -> {
                if (TTManagerHolder.getInitSuccess()) {
                    idoSplash.show();
                } else {
                    if (count >= 5) {
                        canJumpImmediately = true;
                        jumpWhenCanClick();
                    } else {
                        count++;
                        handler.postDelayed(runnable, 300);
                    }
                }
            };
        }
    }
}
